package com.jodie.store.controller;

import com.jodie.store.controller.ex.*;
import com.jodie.store.entity.User;
import com.jodie.store.service.IUserService;
import com.jodie.store.service.ex.InsertException;
import com.jodie.store.service.ex.UsernameDuplicatedException;
import com.jodie.store.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.print.DocFlavor;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Jodie
 * @date 2023/2/3-12:14
 */
// @Controller
@RestController // @Controller + @ResponseBody
@RequestMapping("users")
public class UserController extends BaseController{
    @Autowired
    private IUserService userService;

    @RequestMapping("register")
    // @ResponseBody //  此方法响应结果以Json格式返回前端
//    public JsonResult<Void> register(User user){
//        JsonResult<Void> result = new JsonResult<>();
//        try {
//            userService.register(user);
//            result.setState(200);
//            result.setMessage("注册成功");
//        } catch (UsernameDuplicatedException e) {
//            result.setState(4000);
//            result.setMessage("用户名被占用");
//        } catch (InsertException e) {
//            result.setState(5000);
//            result.setMessage("注册异常");
//        }
//        return result;
//    }

    // 约定大于配置思想
    // 接收数据方式：pojo类型接收前端的数据，SpringBoot会将前端的url地址中的参数名和pojo类的属性名进行比较，如果名称相同则将值注入到pojo类中对应的属性上
    public JsonResult<Void> register(User user){
        userService.register(user);
        return new JsonResult<>(OK);
    }

    // 非pojo类型，将请求的参数名和方法的参数名进行比较，如果名称相同则自动完成值的依赖注入
    @RequestMapping("login")
    public JsonResult<User> login(String username, String password, HttpSession session){
        User data = userService.login(username,password);
        //session对象中完成数据的绑定(全局)
        session.setAttribute("uid",data.getUid());
        session.setAttribute("username",data.getUsername());
        //获取session中绑定的数据
        System.out.println("uid:"+getuidFromSession(session));
        System.out.println("用户"+getUsernameFromSession(session)+"登录成功！");
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("changePassword")
    public JsonResult<User> changePassword(String oldPassword, String newPassword, HttpSession session){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changePassword(uid,username,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }

    @RequestMapping("getByUid")
    public JsonResult<User> getByUid(HttpSession session){
        User data = userService.getByUid(getuidFromSession(session));
        return new JsonResult<>(OK,data);
    }

    @RequestMapping("changeInfo")
    public JsonResult<User> changeInfo(User user, HttpSession session){
        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        userService.changeInfo(uid,username,user);
        return new JsonResult<>(OK);
    }

    public static final int AVATAR_MAX_SIZE = 10*1024*1024;
    public static final List<String> AVATAR_TYPE = new ArrayList<>();
    static {
        AVATAR_TYPE.add("image/jpeg");
        AVATAR_TYPE.add("image/png");
        AVATAR_TYPE.add("image/bmp");
        AVATAR_TYPE.add("image/gif");
    }
    @RequestMapping("changeAvatar")
    public JsonResult<String> changeAvatar(HttpSession session,
                                           @RequestParam("file") MultipartFile file){
        if(file.isEmpty()){
            throw new FileEmptyException("文件为空");
        }
        if(file.getSize()>AVATAR_MAX_SIZE){
            throw new FileSizeException("文件超出限制");
        }
        if(!AVATAR_TYPE.contains(file.getContentType())){
            throw new FileTypeException("文件类型不支持");
        }

        String parent = session.getServletContext().getRealPath("upload");
        // File对象指向路径，不存在则创建
        File dir = new File(parent);
        if(!dir.exists()){
            dir.mkdirs();
        }
        // 用字符串代替文件名，防止名字相同覆盖
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        // 文件后缀
        String suffix = originalFilename.substring(index);
        String filename = UUID.randomUUID().toString().toUpperCase()+suffix;
        File dest = new File(dir,filename);
        // 参数file文件数据写入空文件dest中
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new FileUploadIOException("文件读写异常");
        } catch (FileStateException e) {
            throw new FileStateException("文件状态异常");
        }

        Integer uid = getuidFromSession(session);
        String username = getUsernameFromSession(session);
        String avatar = "/upload/" + filename;
        userService.changeAvatar(uid,avatar,username);
        return new JsonResult<>(OK,avatar);
    }
}
